package cn.org.guhao.practice.zk.service;

import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

/**
 * ZkService
 *
 * @author guhao
 * @since 2020/6/22
 */
@Service
public class ZkService {

  private static final Logger logger = LoggerFactory.getLogger(ZkService.class);

  private final CuratorFramework curatorFramework;

  public ZkService(CuratorFramework curatorFramework) {
    this.curatorFramework = curatorFramework;
  }

  public void create(String path, int from, int to) {
    for (int i = from; i < to; i++) {
      String keyPath = path + '/' + i;
      try {
        curatorFramework
            .create()
            .creatingParentsIfNeeded()
            .withMode(CreateMode.EPHEMERAL)
            .withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE)
            .forPath(keyPath);
        logger.info("success create node for the path : [{}]", keyPath);
      } catch (Exception e) {
        logger.error("failed to create node", e);
      }
    }
  }

}
